package cn.datawin;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.datawin.crule.CoRule;
import cn.datawin.spider.httputil.HttpClientService;
import cn.datawin.spider.httputil.HttpRequest;
import cn.datawin.spider.httputil.HttpRequest.Method;
import cn.datawin.spider.httputil.HttpResponse;
import cn.datawin.spider.httputil.HttpService;

public class Rule_Baidu extends CoRule{

	
	CooClient client ;
	Service service ;
	@Override
	public void setClient(Client client) {
		this.client = (CooClient)client;
	}

	@Override
	public void setService(Service service) {
		this.service = service;
		
	}

	@Override
	public void first() {
		
		HttpService httpservice = client.getHttpService();
		
		HttpRequest req = new HttpRequest("http://www.baidu.com");
		try {
			HttpResponse res =  httpservice.execute(req);
			String baiduid =  res.getCookies().get("BAIDUID");
			System.out.println(baiduid);
			Result rr = new Result();
			rr.setMap("baiduid", baiduid);
			rr.setMap("sig", "first");
			Collectionss.list.offer(rr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	public void firstResult(){
		Result result = getObject(Result.class);
		String baiduid = (String) result.getMap("baiduid");
		service.setParam("baiduid", baiduid);
		if(baiduid!= null){
			second();
		}
	}
	
	
	public void second(){
		String url = "https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true";
		String baiduid =  (String) service.getParam("baiduid");
		System.out.println(baiduid);
		HttpService httpservice = client.getHttpService();
		
		HttpRequest req = new HttpRequest(url);
		req.setCookie("BAIDUID", baiduid);
		try {
			HttpResponse res =  httpservice.execute(req);
			Pattern pattern = Pattern.compile("bdPass.api.params.login_token='(.+?)';");
			Matcher tokenValMatcher = pattern.matcher(res.getResponseString());
			if(tokenValMatcher.find()){
				String login_token = tokenValMatcher.group(1);
				System.out.println("login_token===="+ login_token);
				Result rr = new Result();
				rr.setMap("login_token", login_token);
				rr.setMap("sig", "second");
				Collectionss.list.offer(rr);
			};
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public void secondResult(){
		Result result = getObject(Result.class);
		String login_token = (String) result.getMap("login_token");
		service.setParam("login_token", login_token);
		if(login_token!= null){
			third();
		}
	}
	
	public void third(){
		String url = "https://passport.baidu.com/v2/api/?login";
		String login_token =  (String) service.getParam("login_token");
		System.out.println(login_token);
		HttpService httpservice = client.getHttpService();
		
		HttpRequest req = new HttpRequest(url,Method.post);
		try {
			String staticPageUrl = "http://www.baidu.com/cache/user/html/jump.html";
			Map<String, String> params=new HashMap<String, String>();
			params.put("charset", "utf-8");
			params.put("token", login_token);
			params.put("isPhone", "false");
			params.put("index", "0");
			params.put("staticpage", staticPageUrl);
			params.put("loginType", "1");
			params.put("tpl", "mn");
			params.put("callback","parent.bdPass.api.login._postCallback");
			params.put("username", "1067611312@qq.com");
			params.put("password", "WANGZENG5566");
			params.put("verifycode", "");
			params.put("mem_pass", "on");

			req.setPostParams(params);
			HttpResponse res =  httpservice.execute(req);
			
			Result result=new Result();
			result.setMap("cookies", res.getCookies());
			result.setMap("sig", "third");
			Collectionss.list.offer(result);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void thirdResult(){
		Result result = getObject(Result.class);
		Map<String, String> cookies =(Map<String, String>) result.getMap("cookies");
		HttpService httpservice = client.getHttpService();
		HashMap<Object, Boolean> cookieNameDict = new HashMap<Object, Boolean>();
		cookieNameDict.put("BDUSS", false);
		cookieNameDict.put("PTOKEN", false);
		cookieNameDict.put("STOKEN", false);

		for (Object objCookieName : cookieNameDict.keySet().toArray()) {
			String strCookieName = objCookieName.toString();
			for (String ck : cookies.keySet()) {
				if (strCookieName.equalsIgnoreCase(ck)) {
					cookieNameDict.put(strCookieName, true);
				}
			}
		}

		boolean bAllCookiesFound = true;
		for (Object objFoundCurCookie : cookieNameDict.values()) {
			bAllCookiesFound = bAllCookiesFound && Boolean.parseBoolean(objFoundCurCookie.toString());
		}

		boolean bLoginBaiduOk = bAllCookiesFound;
		
		HttpRequest req = new HttpRequest("http://www.baidu.com/");
		HttpResponse res = null;
		try {
			res = httpservice.execute(req);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (bLoginBaiduOk) {
			System.out.println("成功模拟登陆百度首页！");
			System.out.println("所返回的HTML源码为：" + res.getResponseString());
			complete();
		} else {
			System.out.println("模拟登陆百度首页 失败！");
			System.out.println("所返回的HTML源码为：" + res.getResponseString());
		}
		
	}
	
	public void complete(){
		System.out.println("==========百度登录 complete=================");
		System.out.println("==========开始抓取url=================");
		
	}
	
	public static void main(String[] args) {
		
	}

	@Override
	public Serializable getSerialize() {
		return null;
	}

	@Override
	public void setSerialize(Serializable obj) {
		
	}

	@Override
	public Service getService() {
		// TODO Auto-generated method stub
		return null;
	}
	
	

}
